﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 
// See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace System.Threading.Actors.Utilities
{
    public static class UtilityMethods
    {
        // Extension method just for dealing with long->int conversion, which is a common headache
        // for those dealing with the JSON "everything is a long" policy.
        // TODO: This is getting complicated.  May need to plumb some of this through ILanguagePackage.
        public static int ToInt(this object value)
        {
            Contract.Requires(value != null);

            if (value is long)
            {
                checked
                {
                    return (int)(long)value;
                }
            }
            else if (value is double)
            {
                return (int)(double)value;
            }
            else if (value is Jurassic.Library.NumberInstance)
            {
                return (int)((Jurassic.Library.NumberInstance)value).Value;
            }
            return (int)value;
        }

        public static string ComputeChecksumString(byte[] buffer)
        {
            Contract.Requires(buffer != null);

            var md5 = MD5.Create(); // Don't know for sure if it's safe to cache a single copy of this...
            var checksum = md5.ComputeHash(buffer);
            var checksumString = BitConverter.ToString(checksum).Replace("-", String.Empty);
            return checksumString;
        }

        // Used internally to create event handler keys for incoming event streams from other actors
        public static string CreateEventHandlerKey(string externalActorName, string eventType, string partitionName = null)
        {
            return String.Format("$EVENTHANDLER${0}${1}${2}", externalActorName, eventType, partitionName);
        }
    }
}
